package net.bwie.jtp.dws.log.job;


import net.bwie.jtp.dws.log.utils.AnalyzerUtil;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.table.annotation.DataTypeHint;
import org.apache.flink.table.annotation.FunctionHint;
import org.apache.flink.table.api.EnvironmentSettings;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.TableEnvironment;
import org.apache.flink.table.functions.TableFunction;
import org.apache.flink.types.Row;

import java.util.List;

public class JtpTrafficSearchKeywordMinuteWindowDwsJob {
    public static void main(String[] args) {
        // 1. 表执行环境
        TableEnvironment tabEnv = getTableEnv() ;

        // 2. 输入表-input：映射到Kafka消息队列
        createInputTable(tabEnv);

        // 3. 数据处理-select
        Table reportTable = handle(tabEnv);

        // 4. 输出表-output：映射到Clickhouse表
        createOutputTable(tabEnv) ;

        // 5. 保存数据-insert
        saveToClickHouse(tabEnv, reportTable) ;
    }

    private static void saveToClickHouse(TableEnvironment tabEnv, Table reportTable) {
        //注册临时表，起名
        tabEnv.createTemporaryView("report_table",reportTable);
        //查询插入
        tabEnv.executeSql(
                "INSERT INTO dws_traffic_search_keyword_window_report_clickhouse_sink\n" +
                        "SELECT\n" +
                        "    DATE_FORMAT(window_start_time,  'yyyy-MM-dd HH:mm:ss')  AS window_start_time,\n" +
                        "    DATE_FORMAT(window_end_time, 'yyyy-MM-dd HH:mm:ss')  AS window_end_time,\n" +
                        "    keyword,\n" +
                        "    keyword_count,\n" +
                        "    ts\n" +
                        "FROM report_table"
        );
    }

    private static void createOutputTable(TableEnvironment tabEnv) {
        tabEnv.executeSql(
                "CREATE TABLE dws_traffic_search_keyword_window_report_clickhouse_sink (\n" +
                        "    `window_start_time` STRING COMMENT '窗口开始日期时间',\n" +
                        "    `window_end_time` STRING COMMENT '窗口结束日期时间',\n" +
                        "    `keyword` STRING COMMENT '搜索关键词',\n" +
                        "    `keyword_count` BIGINT COMMENT '搜索关键词被搜索次数',\n" +
                        "    `ts` BIGINT COMMENT '数据产生时间戳'\n" +
                        ") WITH (\n" +
                        "    'connector' = 'clickhouse',\n" +
                        "    'url' = 'jdbc:clickhouse://node103:8123/jtp_log_report',\n" +
                        "    'table' = 'dws_traffic_search_keyword_window_report',\n" +
                        "    'username' = 'default',\n" +
                        "    'password' = '',\n" +
                        "    'format' = 'json'\n" +
                        ")"
        );
    }

    private static Table handle(TableEnvironment tabEnv) {
        //获取搜索词
        Table searchLogTable = tabEnv.sqlQuery(
                "SELECT\n" +
                        "    page['item'] as full_word,\n" +
                        "    row_time\n" +
                        "FROM dwd_traffic_page_log_kafka_source\n" +
                        "where page['item'] is not null\n" +
                        "    and page['last_page_id'] = 'search'\n" +
                        "    and page['item_type'] = 'keyword'"
        );
        tabEnv.createTemporaryView("search_log_table",searchLogTable);

        //-- s2-使用自定义UDTF函数，进行中文分词

//        tabEnv.createTemporarySystemFunction("ik_analyzer_udtf", IkAnalyzerFunction.class);
//
//
//        Table wordLogTable = tabEnv.sqlQuery(
//                "SELECT\n" +
//                        "    full_word,\n" +
//                        "    keyword,\n" +
//                        "    row_time\n" +
//                        "FROM search_log_table,\n" +
//                        "  LATERAL TABlE(ik_analyzer_udtf(full_word)) as T(keyword)"
//        );

        //-- s2-使用jieba自定义UDTF函数，进行中文分词

        tabEnv.createTemporarySystemFunction("jieba_analyzer_udtf", jiebaAnalyzerFunction.class);

        Table wordLogTable = tabEnv.sqlQuery(
                "SELECT\n" +
                        "    full_word,\n" +
                        "    keyword,\n" +
                        "    row_time\n" +
                        "FROM search_log_table,\n" +
                        "  LATERAL TABlE(jieba_analyzer_udtf(full_word)) as T(keyword)"
        );
        tabEnv.createTemporaryView("word_log_table",wordLogTable);

//        Table reportTable = tabEnv.sqlQuery(
//                "SELECT\n" +
//                        "    TUMBLE_START(row_time, INTERVAL '1' MINUTE) AS window_start_time,\n" +
//                        "    TUMBLE_END(row_time, INTERVAL '1' MINUTE) AS window_end_time,\n" +
//                        "    keyword,\n" +
//                        "    count(keyword) AS keyword_count,\n" +
//                        "    UNIX_TIMESTAMP()*1000 AS ts\n" +
//                        "FROM word_log_table\n" +
//                        "GROUP BY\n" +
//                        "    TUMBLE(row_time, INTERVAL '1' MINUTE),\n" +
//                        "  keyword"
//        );

//        --对前面【搜索关键词汇总统计】中窗口数据计算SQL改用TVF方式书写

        Table reportTable = tabEnv.sqlQuery(
                "SELECT\n" +
                        "    window_start AS window_start_time\n" +
                        "     , window_end AS window_end_time\n" +
                        "     , keyword\n" +
                        "     , count(keyword) AS keyword_count\n" +
                        "     , UNIX_TIMESTAMP() * 1000 AS ts\n" +
                        "FROM TABLE(\n" +
                        "             TUMBLE(TABLE word_log_table, DESCRIPTOR(row_time), INTERVAL '1' MINUTES)\n" +
                        "         ) t1\n" +
                        "GROUP BY window_start, window_end, keyword"
        );




        return reportTable;
    }

    private static void createInputTable(TableEnvironment tabEnv) {

        tabEnv.executeSql(
                "CREATE TABLE dwd_traffic_page_log_kafka_source\n" +
                        "(\n" +
                        "    `common` MAP<STRING, STRING> COMMENT '公共环境信息',\n" +
                        "    `page`   MAP<STRING, STRING> COMMENT '页面信息',\n" +
                        "    `ts`     BIGINT,\n" +
                        "    row_time AS TO_TIMESTAMP(FROM_UNIXTIME(ts / 1000, 'yyyy-MM-dd HH:mm:ss.SSS')),\n" +
                        "    WATERMARK FOR row_time AS row_time - INTERVAL '0' MINUTE\n" +
                        ") WITH (\n" +
                        "    'connector' = 'kafka',\n" +
                        "    'topic' = 'dwd-traffic-page-log',\n" +
                        "    'properties.bootstrap.servers' = 'node101:9092,node102:9092,node103:9092',\n" +
                        "    'properties.group.id' = 'gid_dws_traffic_search_keyword',\n" +
                        "    'scan.startup.mode' = 'earliest-offset',\n" +
                        "    'format' = 'json',\n" +
                        "    'json.fail-on-missing-field' = 'false',\n" +
                        "    'json.ignore-parse-errors' = 'true'\n" +
                        ")"
        );
    }


    private static TableEnvironment getTableEnv(){
        // 1环境属性设置
        EnvironmentSettings settings = EnvironmentSettings.newInstance()
                .inStreamingMode()
                .useBlinkPlanner()
                .build();
        TableEnvironment tabEnv = TableEnvironment.create(settings) ;
        // 2配置属性设置
        Configuration configuration = tabEnv.getConfig().getConfiguration();
        configuration.setString("table.local-time-zone", "Asia/Shanghai");
        configuration.setString("table.exec.resource.default-parallelism", "1");
        configuration.setString("table.exec.state.ttl", "5 s");
        // 3返回对象
        return tabEnv;
    }

// FlinkSQL中自定义UDTF函数，使用IKAnalyzer分词器对搜索词进行分词

    @FunctionHint(output = @DataTypeHint("ROW<keyword STRING>"))
    public static class IkAnalyzerFunction extends TableFunction<Row> {
        public void eval(String fullWord) throws Exception {
            // 中文分词
            List<String> list = AnalyzerUtil.ikAnalyzer(fullWord);
            // 循环遍历输出
            for (String keyword : list) {
                collect(Row.of(keyword));
            }
        }
    }

    // FlinkSQL中自定义UDTF函数，使用jiebaAnalyzer分词器对搜索词进行分词
    @FunctionHint(output = @DataTypeHint("ROW<keyword STRING>"))
    public static class jiebaAnalyzerFunction extends TableFunction<Row> {
        public void eval(String fullWord) throws Exception {
            // 中文分词
            List<String> list = AnalyzerUtil.ikAnalyzer(fullWord);
            // 循环遍历输出
            for (String keyword : list) {
                collect(Row.of(keyword));
            }
        }
    }
}
